#include"func.h"
int main(int argc,char* argv[]){
    // ./5_agent_one 1.pipe 2.pipe
    // 1.pipe读端，2.pipe写端
    ARGS_CHECK(argc,3);
    int fdr = open(argv[1],O_RDONLY);
    ERROR_CHECK(fdr,-1,"read error");
    int fdw = open(argv[2],O_WRONLY);
    ERROR_CHECK(fdw,-1,"write error");

    printf("agent_one is connected\n");

    char buf[1024];
    fd_set rdset;//监听集合

    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(fdr,&rdset);
        //select(fdr+1,&rdset,NULL,NULL,NULL);
        
        //添加聊天超时时间
        struct timeval timeout;
        timeout.tv_sec = 3;
        timeout.tv_usec = 0;
        int ret = select(fdr+1,&rdset,NULL,NULL,&timeout);
        //监听是超时，如果在未超时的时候返回了，返回的timeout是剩余的时间戳
        //未超时前，会进行返回剩余的时间，这里检查一下剩余时间
        //
        if(ret!=0){
            //确实会返回timeout剩余值
            printf("sec=%ld,usec=%ld\n",timeout.tv_sec,timeout.tv_usec);
        }
        if(ret == 0){
            printf("timeout!\n");
            time_t now = time(NULL);
            printf("%s\n",ctime(&now));
            continue;
        }

        if(FD_ISSET(fdr,&rdset)){
            //如果1.pipe被写端写入了数据，在这接收数据
            memset(buf,0,sizeof(buf));
            ssize_t res = read(fdr,buf,sizeof(buf));
            printf("buf = %s\n",buf);
            //说明此时写端已经退出了，我这里也可以断开了
            if(res==0){
                printf("the connection is error\n");
                break;
            }
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            //如果从标准输入当中获取到了数据，说明该进行要写管道了
            memset(buf,0,sizeof(buf));
            ssize_t res = read(STDIN_FILENO,buf,sizeof(buf));
            //人为停止ctrl+d
            if(res == 0){
                printf("the connection ending\n");
                break;
            }
            write(fdw,buf,strlen(buf));
        }
    }
}
